<template>
     <div class="qrcode">
    		<div id="reader"></div>
        </div>
</template>
 
<script>
	import { Html5Qrcode } from "html5-qrcode";
	export default {
		created() {
			this.getCameras()
		},
		beforeDestroy() {
		    this.stop();
		},
		methods:{
			getCameras() {
			      Html5Qrcode.getCameras()
			        .then((devices) => {
						 console.log(devices,'devices')
			          if (devices && devices.length) {
						this.html5QrCode = new Html5Qrcode("reader");
			            this.start();
			          }
			        })
			        .catch((err) => {
			          // handle err
					  console.log(err,'rrrr')
					  let title = '您需要授予相机访问权限'
					  if(err =='DOMException: Requested device not found'){
					  	title = '您的设备不支持扫码功能'
					  }else{
						  title = '您需要授予相机访问权限'
					  }
					  this.html5QrCode = new Html5Qrcode("reader");
					  this.$emit("err",title)
			        });
			    },
			 start() {
				 console.log('start1')
			      //environment后置 user前置
			      this.html5QrCode 
			        .start(
			           {facingMode: "environment" },
			          {
			            fps: 2,
			            qrbox: { width: 250, height: 250 }, 
			          },
			          (decodedText, decodedResult) => {
						  this.$emit("ok",decodedText)
						  console.log('start2')
			          }
			        )
			        .catch((err) => {
						console.log('errfff',err)
			            this.$emit("err",err)
			        });
			    },
			    stop() {
			      this.html5QrCode.stop().then((ignore) => {
			          // QR Code scanning is stopped.
			          console.log("QR Code scanning stopped.");
			        })
			        .catch((err) => {
			          // Stop failed, handle it.
			          console.log("Unable to stop scanning.");
			        });
			    },
		}
	}
</script>
 
<style lang="scss" scoped>
	.qrcode{
		    position: relative;
			height: 100%;
			width: 100%;
		  	background: rgba($color: #000000, $alpha: 0.5);
	}
	#reader{
		  top: 45%;
		  left: 0;
		  transform: translateY(-50%);
	}
</style>